package com.changgou.service.impl;

import com.alibaba.fastjson.JSON;

import com.changgou.dao.ESManagerMapper;
import com.changgou.goods.feign.SkuFeign;
import com.changgou.goods.pojo.Sku;
import com.changgou.search.pojo.SkuInfo;

import com.changgou.service.ESManagerService;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.stereotype.Service;


import java.util.List;
import java.util.Map;

@Service
public class ESManagerServiceImpl implements ESManagerService {

    @Autowired
    private ElasticsearchTemplate elasticsearchTemplate;

    @Autowired
    private SkuFeign skuFeign;

    @Autowired
    private ESManagerMapper esManagerMapper;


    //创建索引数据库结构.
    @Override
    public void createIndexAndMapping() {
        //创建索引
        elasticsearchTemplate.createIndex(SkuInfo.class);
        //创建映射
        elasticsearchTemplate.putMapping(SkuInfo.class);

    }

    //将数据库中的所有已上架商品导入到索引库中.
    @Override
    public void importAll() {
        List<Sku> list = skuFeign.findSkuListBySpuId("all");
        if (list == null || list.size() <= 0) {
            throw new RuntimeException("当前数据库中没有上架商品的信息,无法将信息导入商品索引库中");
        }

        /*如果商品集合中有数据,则需要先将list转换成JSON字符串,然后再将JSON字符串转换成SkuInfo集合.
        因为SkuInfo实体类中有索引和映射的关系,和索引库对应,而sku实体类没有索引和映射.*/
        //将List集合转化为JSON
        String jsonList = JSON.toJSONString(list);
        //将JSON转化为SkuInfo集合
        List<SkuInfo> skuInfoList = JSON.parseArray(jsonList, SkuInfo.class);
        //因为Spec为JSON字符串格式,所以需要将规格转换成map格式,存储到specMap属性中
        for (SkuInfo skuInfo : skuInfoList) {
            Map mapSpec = JSON.parseObject(skuInfo.getSpec(), Map.class);
            skuInfo.setSpecMap(mapSpec);
        }

        //导入索引库
        esManagerMapper.saveAll(skuInfoList);


    }

    //将消息队列监听到的上架商品存储到索引库中
    @Override
    public void importDataToEsByspuId(String spuId) {
        List<Sku> list = skuFeign.findSkuListBySpuId(spuId);
        if (list == null || list.size() <= 0) {
            throw new RuntimeException("当前数据库中没有需要上架商品的信息,无法将信息导入商品索引库中");
        }
        //将集合转换为JSON
        String jsonSkuList = JSON.toJSONString(list);
        //将JSON转换为SkuInfo
        List<SkuInfo> skuInfos = JSON.parseArray(jsonSkuList, SkuInfo.class);
        //将规格信息由字符串转换成map
        for (SkuInfo skuInfo : skuInfos) {
            Map map = JSON.parseObject(skuInfo.getSpec(), Map.class);
            skuInfo.setSpecMap(map);
        }
        //添加到索引库
        esManagerMapper.saveAll(skuInfos);
    }

    @Override
    public void deleteDataByspuId(String spuId) {
        List<Sku> skuInfoList = skuFeign.findSkuListBySpuId(spuId);
        if (skuInfoList == null || skuInfoList.size() <= 0) {
            throw new RuntimeException("当前数据没有查询到,无法从索引库删除");
        }
        for (Sku sku : skuInfoList) {
            esManagerMapper.deleteById(Long.parseLong(sku.getId()));
        }

    }


}
